const https = require('https');
const DataStore = require('../app-store');
const dataStore = new DataStore();
const solo = "www.luckycxy.com";

//上传文章到solo
exports.publishArticleToSolo = function publishArticleToSolo(title, content, isPublish, extParams) {
    return new Promise((resolve, reject) => {
        let article = {
            'articleTitle': extParams.hasOwnProperty('title') ? extParams['title'] : title ,
            'articleContent': extParams.hasOwnProperty('content') ? extParams['content'] :content,
            'articleAbstract': extParams.hasOwnProperty('articleAbstract') ? extParams['articleAbstract'] : '',
            'articleTags': extParams.hasOwnProperty('articleTags') ? extParams['articleTags'] : '',
            'articlePermalink': extParams.hasOwnProperty('articlePermalink') ? extParams['articlePermalink']: '',
            'articleStatus': isPublish ? 0 : 1,
            'articleSignId': extParams.hasOwnProperty('articleSignId') ? extParams['articleSignId'] : '1',
            'postToCommunity': false,
            'articleViewPwd': extParams.hasOwnProperty('articleViewPwd') ? extParams['articleViewPwd'] : ''
        };
        let data = JSON.stringify({'article':article});
        let headers = {};
        //获取Cookie
        headers['Cookie'] = dataStore.getSoloCookies();
        headers["user-agent"] = "Mozilla/5.0";
        headers['referer'] = solo+'/admin-index.do';
        headers['origin'] = solo;
        headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
        headers['x-requested-with'] = 'XMLHttpRequest';
        headers['Connection'] = 'keep-alive';
        headers['Accept-Language'] = 'zh-CN,zh;q=0.9';
        // headers['Accept-Encoding'] = 'gzip, deflate, br';
        headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
        //自己的headers属性在这里追加
        let request = https.request({
            host: 'www.luckycxy.com',
            port: 443,
            path: '/console/article/',
            method: 'POST',
            referer: solo+'/admin-index.do',
            origin: solo,
            headers: headers
        }, function (res) {
            let value = '';
            res.on('data', function (buffer) {
                    value += buffer;
                }
            );
            res.on('end', () => {
                if (res.statusCode === 200) {
                    const result = JSON.parse(value);
                    resolve(result.request)
                } else {
                    reject('发布失败:' + value)
                }
            });
        });
        request.on('error', function (e) {
            console.log('problem with request: ' + e.message);
            reject('网络连接异常')
        });
        request.write( data );
        request.end();
    })
};
